import { getProfileAPI, loginAPI } from '@/api/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    profile: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    // 获取用户权限
    setProfile(state, profile) {
      state.profile = profile
    },
    clearUserInfo(state) {
    // 清除Token
      state.token = ''
      state.profile = {}
      removeToken(TOKEN_KEY)
    }
  },
  actions: {
    async login(context, { username, password }) {
      const res = await loginAPI({ username, password })
      context.commit('setToken', res.data.token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      // 为了permissions.js中使用，这里返回权限数据，触发actions
      return res.data.permissions
    }

  }
}
